/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-08-04 11:37:35
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-08-04 11:37:35
 */
import { useState, useEffect, useRef } from "react";
const useIntervalTimer = (props) => {
  const interval = useRef(null);
  const countRef = useRef(props.count);

  const [hour, setHour] = useState("00");
  const [minute, setMinute] = useState("00");
  const [second, setSecond] = useState("00");
  const [play, setPlay] = useState(props.play);

  useEffect(() => {
    return () => {
      clearInterval(interval.current);
    };
  }, []);

  const formatTime = (seconds) => {
    if (seconds < 0) {
      return;
    }

    let [hour, minute, second] = [0, 0, 0, 0];
    hour = Math.floor(seconds / (60 * 60));
    minute = Math.floor(seconds / 60) - hour * 60;
    second = Math.floor(seconds) - hour * 60 * 60 - minute * 60;

    let resultHour: string = hour < 10 ? String("0" + hour) : String(hour);
    let resultMinute: string =
      minute < 10 ? String("0" + minute) : String(minute);
    let resultSecond: string =
      second < 10 ? String("0" + second) : String(second);

    setHour(resultHour);
    setMinute(resultMinute);
    setSecond(resultSecond);
  };

  useEffect(() => {
    if (props.play !== play) {
      setPlay(props.play);
      clearInterval(interval.current);
      interval.current = null;
      start();
    }
  }, [props.play]);

  const start = () => {
    if (props.play === false) {
      return;
    }

    interval.current = setInterval(() => {
      countRef.current = countRef.current - 1;
      formatTime(countRef.current);
      if (countRef.current == 0) {
        console.log("interval.current", interval.current);
        clearInterval(interval.current);
      }
    }, 1000);
  };

  return {
    hour,
    minute,
    second,
    start,
    current: countRef.current,
  };
};

export default useIntervalTimer;
